package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 2021/3/4 下午10:02
 *
 * https://leetcode-cn.com/problems/longest-increasing-subsequence/
 */
public class _300_最长递增子序列 {

    public static int lengthOfLIS(int[] nums) {

        int len = nums.length;

        int[] lenMins = new int[len];
        lenMins[0]  = nums[0];
        int lastLen = 1;
        for (int i = 1; i < len; i++) {

            int val = nums[i];
            if (lenMins[lastLen - 1] < val) {

                lenMins[lastLen] = val;
                lastLen++;
            }else {

                int index = findLGIndex(lenMins,0,lastLen - 1,nums[i]);
                lenMins[index] = val;
            }
        }

        return lastLen;
    }

    private static int findLGIndex(int[] lenMins, int l, int r, int val) {

        int mid = 0;

        while (l < r) {

            mid = ((r - l) >> 1) + l;
            if (lenMins[mid] < val) {

                l = mid + 1;
            }else {

                r = mid;
            }
        }
        return l;
    }

    /**
     *
     * O(n^2)
     * @param nums
     * @return
     */
    public static int lengthOfLIS01(int[] nums) {

        int len = nums.length;
        int[] lens = new int[len];
        lens[0] = 1;

        int maxLen = 1;
        for (int i = 1; i < len; i++) {

            int tmpLen = 1;

            for (int j = 0; j < i ; j++) {

                if (nums[i] > nums[j]) {

                    tmpLen = Math.max(tmpLen,lens[j] + 1);
                }
            }
            lens[i] = tmpLen;

            maxLen = Math.max(maxLen,tmpLen);
        }

        return maxLen;
    }

    public static void main(String[] args) {

        //[10,9,2,5,3,7,101,18]
//        int[] nums = {10,9,2,5,3,7,101,18};
        int[] nums = {7,7,7,7};
        System.out.println(lengthOfLIS(nums));
    }
}
